<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <base href="<%=request.getContextPath()%>/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科室管理 - 医疗预约系统后台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="statics/css/hisStyle.css">
    <link rel="stylesheet" href="statics/css/common-styles.css">
</head>
<body>
<!-- 侧边栏 -->
<%@include file="../common/sidebar.jsp"%>

<!-- 主内容区域 -->
<div class="main-content">
    <!-- 顶部导航 -->
    <%@include file="../common/top.jsp"%>

    <!-- 内容区域 -->
    <div class="content">
        <div class="function-page">
            <!-- 页面标题 -->
            <div class="page-header">
                <h1>科室管理</h1>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-bar">
                <a href="${pageContext.request.contextPath}/department/toAdd" class="btn btn-primary">
                    <i class="fas fa-plus-circle"></i> 新增科室
                </a>
            </div>

            <!-- 查询表单 -->
            <div class="search-filter">
                <form action="${pageContext.request.contextPath}/department/find" method="post">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="deptname">科室名称：</label>
                            <div class="dropdown-container">
                                <input type="text" id="deptname" name="deptname" 
                                    value="${condition.deptname}" placeholder="请输入科室名称" autocomplete="off" class="form-control">
                                <div id="deptDropdown" class="dropdown-menu">
                                    <!-- 科室选项将通过JavaScript动态填充 -->
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="hospitalid">所属医院：</label>
                            <select id="hospitalid" name="hospitalid" class="form-control">
                                <option value="">全部</option>
                                <c:forEach items="${hospitalList}" var="hospital">
                                    <option value="${hospital.hospitalid}" <c:if test="${condition.hospitalid eq hospital.hospitalid}">selected</c:if>>${hospital.hospitalname}</option>
                                </c:forEach>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> 查询
                            </button>
                            <span class="search-info">总计 ${pageInfo.total} 个科室</span>
                        </div>
                    </div>
                </form>
            </div>

            <!-- 消息提示 -->
            <c:if test="${not empty successMessage}">
                <div class="message success-message" id="successMessage">
                    <i class="fas fa-check-circle"></i> ${successMessage}
                </div>
            </c:if>
            <c:if test="${not empty errorMessage}">
                <div class="message error-message" id="errorMessage">
                    <i class="fas fa-exclamation-circle"></i> ${errorMessage}
                </div>
            </c:if>
            
            <!-- 科室列表 -->
            <div class="data-section">
                <table class="data-table" id="departmentTable">
                    <thead>
                    <tr>
                        <th>科室ID</th>
                        <th>科室名称</th>
                        <th>主治疾病</th>
                        <th>科室设备</th>
                        <th>所属医院</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <c:forEach items="${pageInfo.list}" var="department">
                        <tr>
                            <td>${department.deptid}</td>
                            <td>
                                ${department.deptname}
                            </td>
                            <td>${department.illness}</td>
                            <td>${department.equipment}</td>
                            <td>
                                <c:choose>
                                    <c:when test="${not empty department.hospital and not empty department.hospital.hospitalname}">
                                        ${department.hospital.hospitalname}
                                    </c:when>
                                    <c:otherwise>
                                        <span class="text-muted">未指定</span>
                                    </c:otherwise>
                                </c:choose>
                            </td>
                            <td>
                                <a href="${pageContext.request.contextPath}/department/findById?deptId=${department.deptid}" class="btn btn-secondary btn-sm">
                                    <i class="fas fa-edit"></i> 编辑
                                </a>
                                <button class="btn btn-danger btn-sm delete-btn" 
                                        data-dept-id="${department.deptid}" 
                                        data-dept-name="${department.deptname}">
                                    <i class="fas fa-trash-alt"></i> 删除
                                </button>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页控件 -->
            <span class="pagination-info">共 ${pageInfo.total} 条记录，当前第 ${pageInfo.pageNum} / ${pageInfo.pages} 页</span>
            <div class="pagination-container">
                <div class="pagination">
                    <a href="${pageContext.request.contextPath}/department/find?pageNum=1&deptname=${condition.deptname}&hospitalid=${condition.hospitalid}" 
                       class="pagination-link">
                       <i class="fas fa-angle-double-left"></i> 首页
                    </a>
                    <a href="${pageContext.request.contextPath}/department/find?pageNum=${pageInfo.pageNum-1}&deptname=${condition.deptname}&hospitalid=${condition.hospitalid}" 
                       class="pagination-link ${pageInfo.pageNum == 1 ? 'disabled' : ''}">
                       <i class="fas fa-angle-left"></i> 上一页
                    </a>
                    
                    <!-- 页码遍历 -->
                    <c:forEach begin="1" end="${pageInfo.pages}" var="num">
                        <a href="${pageContext.request.contextPath}/department/find?pageNum=${num}&deptname=${condition.deptname}&hospitalid=${condition.hospitalid}" 
                           class="pagination-link ${pageInfo.pageNum == num ? 'active' : ''}">
                           ${num}
                        </a>
                    </c:forEach>
                    
                    <c:if test="${pageInfo.pageNum < pageInfo.pages}">
                        <a href="${pageContext.request.contextPath}/department/find?pageNum=${pageInfo.pageNum+1}&deptname=${condition.deptname}&hospitalid=${condition.hospitalid}" 
                           class="pagination-link">
                           <i class="fas fa-angle-right"></i> 下一页
                        </a>
                        <a href="${pageContext.request.contextPath}/department/find?pageNum=${pageInfo.pages}&deptname=${condition.deptname}&hospitalid=${condition.hospitalid}" 
                           class="pagination-link">
                           <i class="fas fa-angle-double-right"></i> 末页
                        </a>
                    </c:if>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    // 为侧边栏的科室管理项添加激活状态
    document.addEventListener('DOMContentLoaded', function() {
        const menuItems = document.querySelectorAll('.menu-item');
        menuItems.forEach(item => {
            if (item.getAttribute('href') === 'department/find' || item.getAttribute('href') === '${pageContext.request.contextPath}/department/find') {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });
        
        // 为删除按钮添加事件监听器
        const deleteButtons = document.querySelectorAll('.delete-btn');
        deleteButtons.forEach(button => {
            button.addEventListener('click', function() {
                const deptId = this.getAttribute('data-dept-id');
                const deptName = this.getAttribute('data-dept-name');
                confirmDelete(deptId, deptName);
            });
        });
    });
    
    // 确认删除函数
    function confirmDelete(deptId, deptName) {
        if (confirm('确定删除科室【' + deptName + '】吗？\n\n请注意：\n1. 删除前请确保该科室下没有关联的医生记录\n2. 删除前请确保该科室下没有关联的就诊记录\n3. 删除后数据将无法恢复')) {
            // 使用完整的contextPath构建URL，避免路径解析问题
            window.location.href = '${pageContext.request.contextPath}/department/removeById?deptId=' + deptId;
        }
    }
    // 科室名称下拉列表功能
    document.addEventListener('DOMContentLoaded', function() {
        const deptInput = document.getElementById('deptname');
        const deptDropdown = document.getElementById('deptDropdown');
        let departments = [];
        let allDepartmentsFetched = false; // 标记是否已经获取过所有科室数据

        // 直接从服务器获取所有科室数据（优先方式）
        function fetchAllDepartments() {
            return new Promise((resolve, reject) => {
                console.log('开始从服务器获取所有科室数据...');
                const xhr = new XMLHttpRequest();
                xhr.open('GET', '${pageContext.request.contextPath}/department/getAllDepartments', true);

                // 设置较短的超时时间
                xhr.timeout = 10000;

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        console.log('获取科室数据完成，状态码:', xhr.status);
                        if (xhr.status === 200) {
                            try {
                                console.log('获取到的响应:', xhr.responseText);
                                let response;

                                // 尝试解析响应
                                try {
                                    response = JSON.parse(xhr.responseText);
                                } catch (parseError) {
                                    console.error('JSON解析失败，尝试直接处理响应文本:', parseError);
                                    // 如果解析失败，可能响应已经是科室名称列表
                                    return reject(new Error('响应格式不正确'));
                                }

                                // 验证响应格式
                                if (Array.isArray(response)) {
                                    // 确保每个元素都有deptname属性
                                    const validDepartments = response.map(item => {
                                        if (typeof item === 'string') {
                                            return { deptname: item };
                                        } else if (item && item.deptname) {
                                            return item;
                                        }
                                        return null;
                                    }).filter(Boolean);

                                    console.log('解析并验证后的科室数据数量:', validDepartments.length);
                                    console.log('科室数据示例:', validDepartments.slice(0, 5).map(d => d.deptname).join(', '));
                                    resolve(validDepartments);
                                } else {
                                    console.error('响应不是有效的数组:', response);
                                    reject(new Error('响应不是有效的数组'));
                                }
                            } catch (e) {
                                console.error('处理科室数据时发生意外错误:', e);
                                reject(e);
                            }
                        } else {
                            console.error('获取科室数据失败，状态码:', xhr.status);
                            reject(new Error('服务器错误，状态码: ' + xhr.status));
                        }
                    }
                };

                xhr.onerror = function() {
                    console.error('网络请求发生错误');
                    reject(new Error('网络请求错误'));
                };

                xhr.ontimeout = function() {
                    console.error('请求超时');
                    reject(new Error('请求超时，服务器响应时间过长'));
                };

                xhr.send();
            });
        }

        // 从页面表格中提取科室数据作为备选
        function extractDepartmentsFromTable() {
            const deptNames = new Set();

            // 从表格中提取科室名称
            const departmentRows = document.querySelectorAll('tbody tr');
            console.log('从表格中找到的行数:', departmentRows.length);
            departmentRows.forEach(row => {
                // 获取科室名称单元格（第二列）
                const deptNameCell = row.querySelector('td:nth-child(2)');
                if (deptNameCell) {
                    try {
                        // 提取科室名称，考虑多种格式
                        const fullText = deptNameCell.textContent.trim();
                        // 处理可能的格式："科室名称 (医院名)"
                        let deptName = fullText;
                        const openParenIndex = fullText.indexOf('(');
                        if (openParenIndex > 0) {
                            deptName = fullText.substring(0, openParenIndex).trim();
                        }
                        if (deptName && deptName.length > 0) {
                            deptNames.add(deptName);
                            console.log('从表格提取科室:', deptName);
                        }
                    } catch (e) {
                        console.error('提取科室名称出错:', e);
                    }
                }
            });

            // 转换为数组格式
            const result = Array.from(deptNames).map(name => ({
                deptname: name
            }));
            console.log('从表格提取的科室数量:', result.length);
            return result;
        }

        // 合并并去重科室数据
        function mergeDepartmentData(serverData, tableData) {
            const merged = new Set();

            // 处理服务器数据
            if (Array.isArray(serverData)) {
                serverData.forEach(dept => {
                    if (dept && dept.deptname) {
                        merged.add(dept.deptname);
                        console.log('添加服务器科室:', dept.deptname);
                    }
                });
            }

            // 处理表格数据
            if (Array.isArray(tableData)) {
                tableData.forEach(dept => {
                    if (dept && dept.deptname) {
                        merged.add(dept.deptname);
                    }
                });
            }

            // 转换回数组格式并按名称排序
            const result = Array.from(merged)
                .sort()
                .map(name => ({
                    deptname: name
                }));
            console.log('合并后的科室数量:', result.length);
            return result;
        }

        // 更新科室数据 - 强制使用服务器数据
        async function updateDepartments() {
            console.log('开始更新科室数据...');

            try {
                // 强制从服务器获取所有科室数据
                console.log('强制获取所有科室数据...');
                const serverData = await fetchAllDepartments();

                // 验证服务器返回的数据
                if (Array.isArray(serverData) && serverData.length > 0) {
                    allDepartmentsFetched = true;

                    // 确保每个科室对象都有deptname属性
                    departments = serverData.map(dept => {
                        if (!dept.deptname && typeof dept === 'string') {
                            return { deptname: dept };
                        }
                        return dept;
                    }).filter(dept => dept && dept.deptname);

                    console.log('成功获取所有科室数据，共', departments.length, '个科室');
                } else {
                    console.warn('服务器返回的数据为空或无效');
                    // 回退到备选方案
                    handleServerDataFailure();
                }
            } catch (error) {
                console.warn('从服务器获取数据失败:', error.message);
                // 失败时使用备选数据
                handleServerDataFailure();
            }
        }

        // 处理服务器数据获取失败的情况
        function handleServerDataFailure() {
            // 生成一个包含32个常见科室的完整列表
            const comprehensiveDepartments = [
                {deptname: '内科'},
                {deptname: '外科'},
                {deptname: '儿科'},
                {deptname: '妇产科'},
                {deptname: '眼科'},
                {deptname: '耳鼻喉科'},
                {deptname: '口腔科'},
                {deptname: '皮肤科'},
                {deptname: '神经内科'},
                {deptname: '心内科'},
                {deptname: '呼吸内科'},
                {deptname: '消化内科'},
                {deptname: '肾脏内科'},
                {deptname: '内分泌科'},
                {deptname: '血液科'},
                {deptname: '肿瘤科'},
                {deptname: '骨科'},
                {deptname: '泌尿外科'},
                {deptname: '神经外科'},
                {deptname: '胸外科'},
                {deptname: '普通外科'},
                {deptname: '肝胆外科'},
                {deptname: '心血管外科'},
                {deptname: '烧伤科'},
                {deptname: '麻醉科'},
                {deptname: '急诊科'},
                {deptname: '病理科'},
                {deptname: '放射科'},
                {deptname: '检验科'},
                {deptname: '药剂科'},
                {deptname: '中医科'},
                {deptname: '康复科'}
            ];

            // 直接使用完整的科室列表，不依赖表格数据
            departments = comprehensiveDepartments;
            allDepartmentsFetched = false;

            console.log('使用完整的备用科室数据，共', departments.length, '个科室');
        }

        // 显示下拉列表
        function showDropdown() {
            console.log('显示下拉列表，科室总数:', departments.length);

            // 先清空下拉框
            deptDropdown.innerHTML = '';

            // 获取输入框的值并转换为小写用于过滤
            const filter = deptInput.value.toLowerCase();

            // 过滤科室列表
            const filteredDepts = departments.filter(dept => {
                return dept && dept.deptname &&
                    typeof dept.deptname === 'string' &&
                    dept.deptname.toLowerCase().includes(filter);
            });

            console.log('过滤后的科室数量:', filteredDepts.length);

            // 如果有匹配的科室，创建选项
            if (filteredDepts.length > 0) {
                filteredDepts.forEach(dept => {
                    const option = document.createElement('div');
                    option.textContent = dept.deptname;
                    option.style.padding = '8px 12px';
                    option.style.cursor = 'pointer';
                    option.style.whiteSpace = 'nowrap';
                    option.style.overflow = 'hidden';
                    option.style.textOverflow = 'ellipsis';
                    option.style.borderBottom = '1px solid #f0f0f0';

                    // 添加鼠标悬停效果
                    option.addEventListener('mouseover', function() {
                        this.style.backgroundColor = '#f5f5f5';
                    });

                    option.addEventListener('mouseout', function() {
                        this.style.backgroundColor = '';
                    });

                    // 点击选项时填充输入框并隐藏下拉列表
                    option.addEventListener('click', function() {
                        deptInput.value = dept.deptname;
                        deptDropdown.style.display = 'none';
                    });

                    deptDropdown.appendChild(option);
                });
                deptDropdown.style.display = 'block';
                console.log('下拉列表已显示');
            } else {
                deptDropdown.style.display = 'none';
                console.log('没有匹配的科室，下拉列表已隐藏');
            }
        }

        // 隐藏下拉列表
        function hideDropdown() {
            setTimeout(() => {
                if (!deptInput.contains(document.activeElement) && !deptDropdown.contains(document.activeElement)) {
                    deptDropdown.style.display = 'none';
                }
            }, 200);
        }

        // 刷新科室数据
        async function refreshDepartments() {
            console.log('刷新科室数据...');
            await updateDepartments();
            console.log('科室数据刷新完成');
        }

        // 事件监听
        // 输入时过滤并显示下拉列表
        deptInput.addEventListener('input', function() {
            console.log('输入框内容变化，触发下拉列表更新');
            showDropdown();
        });

        // 聚焦时刷新数据并显示下拉列表
        deptInput.addEventListener('focus', async function() {
            console.log('输入框获得焦点，刷新数据并显示下拉列表');
            await refreshDepartments();
            showDropdown();
        });

        // 点击页面其他地方隐藏下拉列表
        document.addEventListener('click', function(e) {
            if (!deptInput.contains(e.target) && !deptDropdown.contains(e.target)) {
                hideDropdown();
            }
        });

        // 阻止下拉列表点击事件冒泡
        deptDropdown.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 点击输入框时刷新数据并显示下拉列表
        deptInput.addEventListener('click', async function(e) {
            e.stopPropagation();
            console.log('输入框被点击，刷新数据并显示下拉列表');
            await refreshDepartments();
            showDropdown();
        });

        // 初始化加载科室数据 - 立即执行
        console.log('初始化加载科室数据...');
        updateDepartments().then(() => {
            console.log('初始化科室数据加载完成');
            // 初始加载完成后，准备好数据，但不立即显示下拉列表
        });

        // 添加一个简单的手动测试按钮（可选）
        function addDebugButton() {
            const debugButton = document.createElement('button');
            debugButton.textContent = '测试科室数据';
            debugButton.style.marginLeft = '10px';
            debugButton.addEventListener('click', async function() {
                await refreshDepartments();
                console.log('当前科室数据:', departments);
                alert('科室数量: ' + departments.length + '\n' +
                    '前5个科室: ' + departments.slice(0, 5).map(d => d.deptname).join(', '));
            });
            deptInput.parentNode.appendChild(debugButton);
        }

        // 为了确保数据正确加载，我们强制在页面加载后再次获取数据
        setTimeout(() => {
            console.log('3秒后强制刷新科室数据...');
            refreshDepartments();
        }, 3000);
        
        
        // 消息自动消失
        document.addEventListener('DOMContentLoaded', function() {
            // 成功消息3秒后消失
            const successMessage = document.getElementById('successMessage');
            if (successMessage) {
                setTimeout(function() {
                    successMessage.style.display = 'none';
                }, 3000);
            }
            
            // 错误消息5秒后消失
            const errorMessage = document.getElementById('errorMessage');
            if (errorMessage) {
                setTimeout(function() {
                    errorMessage.style.display = 'none';
                }, 5000);
            }
        });
    });
</script>
</body>
</html>